package com.xinghen.ace.common.exception;

import com.xinghen.ace.common.constant.CommonConstants;
import com.xinghen.ace.common.exception.auth.ClientTokenException;
import com.xinghen.ace.common.exception.auth.UserTokenException;
import com.xinghen.ace.common.response.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @author xinghen
 * @ClassName: GlobalExceptionHandler
 * @Package: com.xinghen.ace.common.exception
 * @Description 全局异常处理器
 * @create 2018-05-04 11:27
 */
@Slf4j
@ControllerAdvice(basePackages = "com.xinghen.ace")
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(BaseException.class)
    public RestResult baseExceptionHandler(HttpServletResponse response, BaseException ex) {
        log.error(ex.getMessage(), ex);
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return RestResult.error(ex.getStatus(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public RestResult otherExceptionHandler(HttpServletResponse response, Exception ex) {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        log.error(ex.getMessage(), ex);
        return RestResult.error(CommonConstants.EX_OTHER_CODE, ex.getMessage());
    }

    @ExceptionHandler(ClientTokenException.class)
    public RestResult clientTokenExceptionHandler(HttpServletResponse response, ClientTokenException ex) {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        log.error(ex.getMessage(), ex);
        return RestResult.error(ex.getStatus(), ex.getMessage());
    }

    @ExceptionHandler(UserTokenException.class)
    public RestResult userTokenExceptionHandler(HttpServletResponse response, UserTokenException ex) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        log.error(ex.getMessage(), ex);
        return RestResult.error(ex.getStatus(), ex.getMessage());
    }

}
